 <?php
/**
 * 推荐位数据模型
 * BasePositionModel.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author Huangdaohai
 * @email huangdaohai.2007@163.com
 * @version $Id$
 * @access public
 */
class BasePositionModel extends BaseModel
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return BasePositionModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{base_position}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('position_name', 'required'),
			array('model_id, cate_id, max_number, sort, disable', 'numerical', 'integerOnly'=>true),
			array('position_name', 'length', 'max'=>20),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('posid, model_id, cate_id, position_name, max_number, sort, disable', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'modelinfo' => array(self::HAS_ONE,'CmsModel' ,'' ,'on'=>'t.model_id=modelinfo.model_id') ,
            'cateinfo' => array(self::HAS_ONE ,'CategoryModel' , '' ,'on'=>'t.cate_id=cateinfo.cate_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'posid' => 'ID',
			'model_id' => '所属模型',
			'cate_id' => '所属栏目',
			'position_name' => '推荐位名称',
			'max_number' => '允许数量',
			'sort' => '排序',
			'disable' => '禁用'
		);
	}    
    /**
	 * 获取推荐位
	 *
	 * @param array $params
	 * @return array 数据数组和分页对象
	 */
	public function getList($params){
		$iPage = (isset($params['page']) && !empty($params['page'])) ? $params['page'] : 1;
		$iPagesize = (isset($params['pagesize']) && !empty($params['pagesize'])) ? $params['pagesize'] : Yii::app()->params->pageSize;

		$criteria = new CDbCriteria();
        $criteria->order = 't.sort ASC ,t.posid DESC' ;//排序条件 		
		$iCcount = self::model()->with(array('modelinfo'=>array('select'=>'model_name')))->with(array('cateinfo'=>array('select'=>'cate_name')))->count($criteria);
		$oPages = new CPagination($iCcount);
		$oPages->pageSize = $iPagesize;
		$oPages->setCurrentPage($iPage-1);
		$oPages->applyLimit($criteria);
		$oResult = self::model()->with(array('modelinfo'=>array('select'=>'model_name')))->with(array('cateinfo'=>array('select'=>'cate_name')))->findAll($criteria);

		$aList = array();
		if(!empty($oResult)){
			foreach ($oResult as $iKey => $aVal){
				$aList[$aVal->posid]['posid'] = $aVal->posid;
                $aList[$aVal->posid]['model_id'] = isset($aVal->modelinfo->model_name) ? $aVal->modelinfo->model_name : '全部';
                $aList[$aVal->posid]['cate_id'] = isset($aVal->cateinfo->cate_name) ? $aVal->cateinfo->cate_name : '全部';
                $aList[$aVal->posid]['position_name'] = $aVal->position_name;
                $aList[$aVal->posid]['max_number'] = $aVal->max_number;
                $aList[$aVal->posid]['sort'] = $aVal->sort;
                $aList[$aVal->posid]['disable'] = $aVal->disable;
			}
		}
		$listResult['list'] = $aList;
		$listResult['pages'] = $oPages;

		return $listResult;
	}
    /**
     * BasePositionModel::getAllPosition() 调取所有推荐位ID
     * 
     * @param mixed $params
     * @return
     */
    public static function getAllPosition($params){
        $criteria = new CDbCriteria();
        $criteria->addCondition('disable=1');
        //合成筛选条件
        if( isset($params['model_id']) && $params['model_id'] ){
            $criteria->addCondition('model_id='.$params['model_id'] ,'OR');
        }
        if( isset($params['cate_id']) && $params['cate_id'] ){
            $criteria->addCondition('cate_id='.$params['cate_id'],'OR');
        }
        $criteria->order = 't.sort ASC ,t.posid ASC' ;//排序条件
        $oResult = self::model()->findAll($criteria);

		$aList = array();
		if(!empty($oResult)){
			foreach ($oResult as $iKey => $aVal){
				$aList[$aVal->posid] = $aVal->position_name;
			}
		};

		return $aList;
    }
    /**
     * AdminCategory::saveData() 保存数据
     * 
     * @param array $attributes 属性数组
     * @param bool $isverify 是否验证
     * @return mix 保存成功返回 主键ID  失败返回错误数组
     */
    public function saveData($attributes ,$isverify=true){
        $this->attributes=$attributes;
        if( $isverify ){
            if( $this->save() ){
                //保存成功             
                return $this->cate_id;
            } else {
                return $this->errors;
            }
        } else {
            $this->save(false);
            return $this->cate_id;
        }        
    }
    /**
     * BasePositionModel::deleteData() 删除数据
     * 
     * @param int $posid 推荐位ID
     * @return bool  真或假
     */
    public function deleteData($posid){
        //
        $oModel = self::model()->findByPk($posid);
        if( empty( $oModel ) ){
            return false;
        }
        //删除推荐所有数据
        $oPositionData = new BasePositionDataModel();
        $oPositionData->deleteData('posid='.$oModel->posid);
        if($oModel->delete()){
            return true;
        }
        return false;
    }
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('posid',$this->posid);
		$criteria->compare('model_id',$this->model_id);
		$criteria->compare('cate_id',$this->cate_id);
		$criteria->compare('position_name',$this->position_name,true);
		$criteria->compare('max_number',$this->max_number);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('disable',$this->disable);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}